import { post } from '@/utils/ajax'
import { ElMessage as Message } from 'element-plus'

// 地址常量
const url = {
    isNeedSelectUser: "/wf/manager/instance/isNeedSelectUser",
    startWfInstance: "/wf/manager/instance/startWfInstance",
    completeTask: "/wf/task/todo/completeTask",
    updateAndCompleteTask: "/wf/task/todo/updateAndCompleteTask",
    claimTask: "/wf/task/todo/claimTask",
    unClaimTask: "/wf/task/todo/unClaimTask",
    addBeforeTask: "/wf/task/todo/addBeforeTask",
    addAfterTask: "/wf/task/todo/addAfterTask",
    rejectedTaskTarget: "/wf/task/todo/rejectedTaskToTargetNode",
    getRejectedEnableNodes: "/wf/task/todo/getRejectedEnableNodes",
    transferTask: "/wf/task/todo/transferTask",
    getBeforeRejectedEnableNodes: "/wf/task/todo/getBeforeRejectedEnableNodes",
    rejectToStarter: "/wf/task/todo/rejectToStart",
}

/**
 * 是否需要选择下一步处理人
 *
 * @param {String} wfCode 流程编码
 * @param {String} taskId 任务ID
 * @param {String} isApprove 是否同意，'true'表示同意
 * @param {Object} params 参数对象
 * @param {Function} needCallback 需要选人回调
 * @param {Function} notNeedCallback 不需要选人回调
 */
export function isNeedSelectUser(wfCode, taskId, isApprove, params, needCallback, notNeedCallback) {
    wfCode = wfCode || '';
    taskId = taskId || '';
    isApprove = isApprove || '';
    params = params || {};
    const completeFirst = (params && params.completeFirst) || false;
    if (wfCode === '' && taskId === '') {
        Message({
            message: "流程编码和任务ID不可同时为空",
            type: 'error'
        })
        return;
    }
    return post(url.isNeedSelectUser, { wfCode, taskId, completeFirst, isApprove, params }, { objectAsMap: true }).then(res => {
        if (res.code === '200' || res.code === 200) {
            if (res.data === 'true') {
                needCallback();
            } else {
                notNeedCallback();
            }
        } else {
            Message({
                message: res.msg,
                type: 'error'
            })
        }
    });
}

/**
 * 启动工作流
 * @param wfCode 流程编码
 * @param businessKey 业务主键
 * @param businessSubject 业务主题
 * @param params 其他流程参数
 */
export function startWfInstance(compoment, wfCode, businessKey, businessSubject, params, callbackFunc) {
    // 删除启动人参数，后台从Session获取
    params && delete params.starter;

    var newParams = {};
    newParams.wfCode = wfCode || '';
    newParams.businessKey = businessKey || '';
    newParams.businessSubject = businessSubject || '';
    newParams.candidates = (params && params.candidates) || '';
    newParams.completeFirst = (params && params.completeFirst) || false;
    newParams.params = params || {};
    return post(url.startWfInstance, newParams, { objectAsMap: true }).then(response => {
        if (typeof callbackFunc === 'function') { // 有指定回调函数优先调用
            callbackFunc(response);
        } else {// 什么都不做，直接关闭
            compoment && typeof compoment.close === 'function' && compoment.close();
            // if (compoment) {
            //     compoment.selectUserParam = {};
            //     compoment.selectUserOpen = false;
            //     compoment.cancel();
            // }
        }
    });
}

/**
 * 驳回流程发起人
 *
 * @param taskId 待办任务ID
 * @param approveComment 审批意见
 * @param ccUserId 抄送用户id
 * @param params 流程参数
 * @param callbackFunc 回调函数
 */
export function rejectToStarter(compoment, taskId, approveComment, ccUserId, params, callbackFunc) {
    var newParams = params || {};
    newParams.toStart = "true";

    Message({ message: "正在驳回至流程发起人，请稍等...", type: 'info' });
    return post(url.rejectToStarter, {taskId, approveComment, ccUserId, newParams}, {objectAsMap: true}).then(response => {
        if (response.code == '200' || response.code === 200) {
            Message({ message: "驳回至流程发起人成功!", type: 'success' });
            if (typeof callbackFunc === 'function') { // 有指定回调函数优先调用
                callbackFunc(response);
            } else {
                // 什么都不做，直接关闭
                compoment && typeof compoment.close === 'function' && compoment.close('passHandler', params);
            }
        } else {
            Message({ message: response.msg, type: 'error' });
            return;
        }
    })
}

/**
 * 启动工作流并选择下一步处理
 * @param wfCode 流程编码
 * @param businessKey 业务主键
 * @param businessSubject 业务主题
 * @param params 其他流程参数
 */
export function startWfInstanceAndSelectUser(compoment, wfCode, businessKey, businessSubject, params, callbackFunc) {
    wfCode = wfCode || '';
    businessKey = businessKey || '';
    businessSubject = businessSubject || '';
    // 删除启动人参数，后台从Session获取
    params && delete params.starter;
    isNeedSelectUser(wfCode, null, null, params, function () {
        const completeFirst = (params && params.completeFirst) || false;
        //选择下一步处理
        var dest = { wfCode, businessKey, businessSubject, completeFirst, params };
        if (compoment) {
            compoment.selectUserParam = dest;
            compoment.selectUserOpen = true;
        }
    }, function () {
        //直接启动流程
        startWfInstance(null, wfCode, businessKey, businessSubject, params, callbackFunc);
    });
}

/**
 * 完成待办
 *
 * @param {Object} compoment 审批页面组件
 * @param {String} taskId 任务ID
 * @param {String} isApprove 是否同意：'true'同意
 * @param {String} approveComment 审批意见
 * @param {String} ccUserId 抄送用户ID
 * @param {Object} params 参数
 * @param {Function} callbackFunc 回调函数
 */
export function completeTask(compoment, taskId, isApprove, approveComment, ccUserId, params, callbackFunc) {
    // 删除启动人参数，后台从Session获取
    params && delete params.starter;

    var newParams = {};
    newParams.taskId = taskId || '';
    newParams.isApprove = isApprove || '';
    newParams.approveComment = approveComment || '';
    newParams.candidates = (params && params.candidates) || '';
    newParams.toStart = (params && params.toStart) || "false";
    newParams.ccUserId = ccUserId || '';
    newParams.params = params || {};
    Message({ message: "正在提交，请稍等...", type: 'info' });
    return post(url.completeTask, newParams, { objectAsMap: true }).then(response => {
        if (response.code == '200' || response.code === 200) {
            Message({ message: "提交成功", type: 'success' });
            if (typeof callbackFunc === 'function') { // 有指定回调函数优先调用
                callbackFunc(response);
            } else {
                // 什么都不做，直接关闭
                compoment && typeof compoment.close === 'function' && compoment.close('passHandler', newParams);
            }
        } else {
            Message({ message: response.msg, type: 'error' });
            return;
        }
    });
}

/**
 * 完成待办并选择下一步处理人
 *
 * @param {Object} compoment 审批页面组件
 * @param {String} taskId 任务ID
 * @param {String} isApprove 是否同意：'true'同意
 * @param {String} approveComment 审批意见
 * @param {Object} params 参数
 * @param {Function} callbackFunc 回调函数
 */
export function completeTaskAndSelectUser(compoment, taskId, isApprove, approveComment, ccUserId,params, callbackFunc) {
    taskId = taskId || '';
    isApprove = isApprove || '';
    approveComment = approveComment || '';
    ccUserId = ccUserId || '';
    var wfCode = (params && params.wfCode) || '';
    // 删除启动人参数，后台从Session获取
    params && delete params.starter;
    var dest = { taskId, isApprove, approveComment, ccUserId, wfCode, params };
    // lodash.assign(dest, dest, params);

    if (typeof callbackFunc === 'function') {
        // 有指定回调函数优先调用
        callbackFunc(dest);
    } else {
        // 默认打开窗口
        compoment && typeof compoment.open === 'function' && compoment.open(dest);
    }
}

/**
 * 完成待办（带模型能力）
 *
 * @param {Object} compoment 审批页面组件
 * @param {String} taskId 任务ID
 * @param {String} isApprove 是否同意：'true'同意
 * @param {String} approveComment 审批意见
 * @param {String} ccUserId 抄送用户ID
 * @param {Object} params 参数
 * @param {Function} callbackFunc 回调函数
 */
export function updateAndCompleteTask(compoment, taskId, isApprove, approveComment, ccUserId, params, callbackFunc) {
    // 删除启动人参数，后台从Session获取
    params && delete params.starter;

    var newParams = {};
    newParams.taskId = taskId || '';
    newParams.isApprove = isApprove || '';
    newParams.approveComment = approveComment || '';
    newParams.candidates = (params && params.candidates) || '';
    newParams.toStart = (params && params.toStart) || false;
    newParams.ccUserId = ccUserId || '';
    newParams.params = params || {};
    Message({ message: "正在提交，请稍等...", type: 'info' });
    return post(url.updateAndCompleteTask, newParams, { objectAsMap: true }).then(response => {
        if (response.code == '200' || response.code === 200) {
            Message({ message: "提交成功", type: 'success' });
            if (typeof callbackFunc === 'function') { // 有指定回调函数优先调用
                callbackFunc(response);
            } else {
                // 什么都不做，直接关闭
                compoment && typeof compoment.close === 'function' && compoment.close('passWithModelHandler', newParams);
            }
        } else {
            Message({ message: response.msg, type: 'error' });
            return;
        }
    });
}

/**
 * 完成待办并选择下一步处理人（带模型能力）
 *
 * @param {Object} compoment 审批页面组件
 * @param {String} taskId 任务ID
 * @param {String} isApprove 是否同意：'true'同意
 * @param {String} approveComment 审批意见
 * @param {Object} params 参数
 * @param {Function} callbackFunc 回调函数
 */
export function updateAndCompleteTaskAndSelectUser(compoment, taskId, isApprove, approveComment, ccUserId, params, callbackFunc) {
    taskId = taskId || '';
    isApprove = isApprove || '';
    approveComment = approveComment || '';
    ccUserId = ccUserId || '';
    var wfCode = (params && params.wfCode) || '';
    // 删除启动人参数，后台从Session获取
    params && delete params.starter;
    var dest = { taskId, isApprove, approveComment, ccUserId, wfCode, params };
    // lodash.assign(dest, dest, params);

    if (typeof callbackFunc === 'function') {
        // 有指定回调函数优先调用
        callbackFunc(dest);
    } else {
        // 默认打开窗口
        compoment && typeof compoment.open === 'function' && compoment.open(dest);
    }
}

/**
 * 驳回流程发起人
 *
 * @param taskId 待办任务ID
 * @param approveComment 审批意见
 * @param ccUserId 抄送用户id
 * @param params 流程参数
 * @param callbackFunc 回调函数
 */
/*export function rejectToStarter(compoment, taskId, approveComment, ccUserId, params, callbackFunc) {
    var newParams = params || {};
    newParams.toStart = "true";
    completeTask(compoment, taskId, "false", approveComment, ccUserId,newParams, callbackFunc);
}*/

/**
 * 签入任务
 *
 * @param {Object} compoment 审批页面组件
 * @param {String} taskId 任务ID
 * @param {String} approveComment 审批意见
 * @param {Object} params 参数
 * @param {Function} callbackFunc 回调函数
 */
export function claimTask(compoment, taskId, approveComment, params, callbackFunc){
    Message({ message: "正在签入任务，请稍等...", type: 'info' });
    return post(url.claimTask, {taskId, approveComment, params}, {objectAsMap: true}).then(response => {
        if (response.code == '200' || response.code === 200) {
            Message({ message: "签入任务成功", type: 'success' });
            if (typeof callbackFunc === 'function') { // 有指定回调函数优先调用
                callbackFunc(response);
            } else {
                // 什么都不做，直接关闭
                compoment && typeof compoment.close === 'function' && compoment.close('passHandler', params);
            }
        } else {
            Message({ message: response.msg, type: 'error' });
            return;
        }
    })
}

/**
 * 签出任务
 *
 * @param {Object} compoment 审批页面组件
 * @param {String} taskId 任务ID
 * @param {String} approveComment 审批意见
 * @param {Object} params 参数
 * @param {Function} callbackFunc 回调函数
 */
export function unClaimTask(compoment, taskId, approveComment, params, callbackFunc){
    Message({ message: "正在签出任务，请稍等...", type: 'info' });
    return post(url.unClaimTask, {taskId, approveComment, params}, {objectAsMap: true}).then(response => {
        if (response.code == '200' || response.code === 200) {
            Message({ message: "签出任务成功", type: 'success' });
            if (typeof callbackFunc === 'function') { // 有指定回调函数优先调用
                callbackFunc(response);
            } else {
                // 什么都不做，直接关闭
                compoment && typeof compoment.close === 'function' && compoment.close('passHandler', params);
            }
        } else {
            Message({ message: response.msg, type: 'error' });
            return;
        }
    })
}

/**
 * 转办任务
 *
 * @param {Object} compoment 审批页面组件
 * @param {String} taskId 任务ID
 * @param {String} approveComment 审批意见
 * @param {String} targetUserId 转办用户ID
 * @param {String} ccUserId 抄送用户id
 * @param {Object} params 参数
 * @param {Function} callbackFunc 回调函数
 */
export function transferTask(compoment, taskId, approveComment, targetUserId, ccUserId, params, callbackFunc) {
    Message({ message: "正在转办，请稍等...", type: 'info' });
    return post(url.transferTask, {taskId, approveComment,targetUserId, ccUserId, params}, {objectAsMap: true}).then(response => {
        if (response.code == '200' || response.code === 200) {
            Message({ message: "转办成功!", type: 'success' });
            if (typeof callbackFunc === 'function') { // 有指定回调函数优先调用
                callbackFunc(response);
            } else {
                // 什么都不做，直接关闭
                compoment && typeof compoment.close === 'function' && compoment.close('passHandler', params);
            }
        } else {
            Message({ message: response.msg, type: 'error' });
            return;
        }
    })
}

/**
 * 前加签
 *
 * @param {Object} compoment 审批页面组件
 * @param {String} taskId 任务ID
 * @param {String} approveComment 审批意见
 * @param {String} targetUserId 前加签用户ID
 * @param {String} ccUserId 抄送用户id
 * @param {Object} params 参数
 * @param {Function} callbackFunc 回调函数
 */
export function addBeforeTask(compoment, taskId, approveComment, targetUserId, ccUserId, params, callbackFunc) {
    Message({ message: "正在前加签，请稍等...", type: 'info' });
    return post(url.addBeforeTask, {taskId, approveComment,targetUserId, ccUserId, params}, {objectAsMap: true}).then(response => {
        if (response.code == '200' || response.code === 200) {
            Message({ message: "前加签成功!", type: 'success' });
            if (typeof callbackFunc === 'function') { // 有指定回调函数优先调用
                callbackFunc(response);
            } else {
                // 什么都不做，直接关闭
                compoment && typeof compoment.close === 'function' && compoment.close('passHandler', params);
            }
        } else {
            Message({ message: response.msg, type: 'error' });
            return;
        }
    })
}

/**
 * 后加签
 *
 * @param {Object} compoment 审批页面组件
 * @param {String} taskId 任务ID
 * @param {String} approveComment 审批意见
 * @param {String} targetUserId 后加签用户ID
 * @param {String} ccUserId 抄送用户id
 * @param {Object} params 参数
 * @param {Function} callbackFunc 回调函数
 */
export function addAfterTask(compoment, taskId, approveComment, targetUserId, ccUserId, params, callbackFunc) {
    Message({ message: "正在后加签，请稍等...", type: 'info' });
    return post(url.addAfterTask, {taskId, approveComment,targetUserId, ccUserId, params}, {objectAsMap: true}).then(response => {
        if (response.code == '200' || response.code === 200) {
            Message({ message: "后加签成功!", type: 'success' });
            if (typeof callbackFunc === 'function') { // 有指定回调函数优先调用
                callbackFunc(response);
            } else {
                // 什么都不做，直接关闭
                compoment && typeof compoment.close === 'function' && compoment.close('passHandler', params);
            }
        } else {
            Message({ message: response.msg, type: 'error' });
            return;
        }
    })
}

/**
 * 获取可驳回的节点列表
 * @param taskId
 */
export function getRejectedEnableNodes(taskId) {
    return post(url.getRejectedEnableNodes, {taskId} )
}

/**
 * 完成待办
 *
 * @param {Object} compoment 审批页面组件
 * @param {String} taskId 任务ID
 * @param {String} isApprove 是否同意：'true'同意
 * @param {String} approveComment 审批意见
 * @param {Object} rejectNode 驳回节点
 * @param {Object} params 参数
 * @param {Function} callbackFunc 回调函数
 */
export function rejectedTaskTarget(compoment, taskId, isApprove, approveComment, rejectNode, params, callbackFunc) {
    // 删除启动人参数，后台从Session获取
    params && delete params.starter;

    let newParams = {};
    newParams.taskId = taskId || '';
    newParams.isApprove = isApprove || '';
    console.log("targetNode"+JSON.stringify(rejectNode))
    newParams.targetNodeId = rejectNode|| '';
    newParams.approveComment = approveComment || '';
    newParams.candidates = (params && params.candidates) || '';
    newParams.params = params || {};
    Message({ message: "正在驳回到指定节点，请稍等...", type: 'info' });
    return post(url.rejectedTaskTarget, newParams, { objectAsMap: true }).then(response => {
        if (response.code == '200' || response.code === 200) {
            Message({ message: "驳回成功", type: 'success' });
            if (typeof callbackFunc === 'function') { // 有指定回调函数优先调用
                callbackFunc(response);
            } else {
                // 什么都不做，直接关闭
                compoment && typeof compoment.close === 'function' && compoment.close('passHandler', newParams);
            }
        } else {
            Message({ message: response.msg, type: 'error' });
            return;
        }
    });
}


